#!/usr/bin/env bash
. ./scripts/devcontainer/_assert-in-container "$0" "$@"

set -euo pipefail

# collect args
PUBLISHED=false
RESTART=true
for i in "$@"
do
  case "${i}" in
    --published)
    PUBLISHED=true
    shift
    ;;
  esac
  case "${i}" in
    --restart=no)
    RESTART=false
    shift
    ;;
  esac
done


# misc config and helpers
grey="\033[1;30m"
reset="\033[0m"

function announce() {
  msg="$1"
  filename="$2"
  filename=$(realpath "$filename" --relative-to .)
  echo -e "$msg ($grey$filename$reset)"
}

LOGS="${DARK_CONFIG_RUNDIR}/logs"
MIGRATIONS_LOG="$LOGS/migrations.log"

function exe_path() {
  local service="$1"
  if [[ "$PUBLISHED" == "true" ]]; then
    echo "backend/Build/out/${service}/Release/net8.0/linux-x64/publish/${service}"
  else
    echo "backend/Build/out/${service}/Debug/net8.0/${service}"
  fi
}

BWDSERVER_EXE=$(exe_path "BwdServer")
BWDSERVER_LOG="$LOGS/bwdserver.log"
CRONCHECKER_EXE=$(exe_path "CronChecker")
CRONCHECKER_LOG="$LOGS/cronchecker.log"
QUEUEWORKER_EXE=$(exe_path "QueueWorker")
LOCALEXEC_EXE=$(exe_path "LocalExec")


# (actual logic starts here)

# If this script was called with `--restart=no`,
# we should exit early if everything is already running
if [[ $(pgrep BwdServer -c) -eq 0 ]]; then RESTART=true; fi
if [[ $(pgrep CronChecker -c) -eq 0 ]]; then RESTART=true; fi
if [[ $(pgrep QueueWorker -c) -eq 0 ]]; then RESTART=true; fi
if [[ "${RESTART}" == "false" ]]; then
  echo "Servers are running and we don't need to restart"
  exit 0
fi

# Otherwise, stop the server processes now; we'll start them back up again shortly
echo "Stopping servers"
sudo pkill -f "BwdServer" || true
sudo pkill -f "CronChecker" || true
sudo pkill -f "QueueWorker" || true


# Run the PubSub emulator (used for QueueWorker stuff)
./scripts/run-pubsub-emulator


# Wait for any builds that haven't been yet compiled
echo "Waiting for builds to be ready"
for ((i=1;i<=1000;i++));
do
  if [[
     ! -f "${BWDSERVER_EXE}" || \
     ! -f "${CRONCHECKER_EXE}" || \
     ! -f "${QUEUEWORKER_EXE}" || \
     ! -f "${LOCALEXEC_EXE}" ]]; then
    sleep 0.01
  fi
done
echo "Done waiting for builds to be ready"


announce "Running migrations" "${MIGRATIONS_LOG}"
"${LOCALEXEC_EXE}" migrations run > "${MIGRATIONS_LOG}" 2>&1

announce "Running bwdserver" "${BWDSERVER_LOG}"
"${BWDSERVER_EXE}" > "${BWDSERVER_LOG}" 2>&1 &

announce "Running cronchecker" "${CRONCHECKER_LOG}"
"${CRONCHECKER_EXE}" > "${CRONCHECKER_LOG}" 2>&1 &

QUEUEWORKER_LOG="$LOGS/queueworker.log"
announce "Running queueworker" "${QUEUEWORKER_LOG}"
"${QUEUEWORKER_EXE}" > "${QUEUEWORKER_LOG}" 2>&1 &

echo "Finished loading servers"